import {Component, OnInit} from '@angular/core';
import {Article, ArticleListService, Column} from '../services/article-list.service';
import {ActivatedRoute} from '@angular/router';
import {AppService} from '../services/app.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
  parentArticleCategoryId: string;
  articleList: Article[] = [];
  columnList: Column[] = [];
  searchTitle = '';

  constructor(
    private routeInfo: ActivatedRoute,
    private articleListService: ArticleListService,
    private appService: AppService) {
    appService.setPageTitle('文章列表');
  }

  ngOnInit() {
    this.routeInfo.params.subscribe(params => {
      this.parentArticleCategoryId = params.parentArticleCategoryId;
      this.getArticleColumn();
    });
  }

  /**
   * 更新查询条件，用查询条件列表
   * @param {string} event 查询条件
   */
  searchList(event: string) {
    this.searchTitle = event;
    this.getArticleColumn();
  }

  /**
   * 获取文章栏目列表
   * @param {string} parentArticleCategoryId 当前栏目列表id
   */
  getArticleColumn(parentArticleCategoryId: string = this.parentArticleCategoryId) {
    this.articleListService.getArticleColumn({
      parentArticleCategoryId: parentArticleCategoryId,
      Look: 0,
      sort: 0,
      type: 0,
      title: this.searchTitle,
      isRecommend: -1,
      isStick: -1,
      isEnabled: -1,
      start: 0,
      num: 20
    }).subscribe(data => {
      const columnList: Column[] = [], articleList: Article[] = [];
      data.forEach(item => {
        if (item.hasOwnProperty('articleCategoryId')) {
          columnList.push(<Column>item);
        } else if (item.hasOwnProperty('articleId')) {
          articleList.push(<Article>item);
        }
      });
      this.columnList = columnList;
      this.articleList = articleList;
    });
  }
}
